﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Reflection;
using System.Linq;


namespace ArcGisMapDesktop
{
    public class JsonHelper
    {




        public static string ToNewJson<T>(T t)
        {
            return JsonConvert.SerializeObject(t);
        }
        /// <summary>  
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串  
        /// </summary>  
        private string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }




        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            return JsonConvert.DeserializeObject<T>(szJson);
        }
        public static object ToJsonObject(string jsonString)
        {
            object objs = JsonConvert.DeserializeObject(jsonString);
            return objs;
        }
        private string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("///Date({0}+0800)///", ts.TotalMilliseconds);
            return result;
        }
        public static string GetDictionaryValue(string key, Object dataobj)
        {
            Dictionary<string, object> data = dataobj as Dictionary<string, object>;
            return GetDictionaryValue(key, data);
        }
        public static string GetDictionaryValue(string key, Dictionary<string, object> data)
        {
            if (data.ContainsKey(key))
            {
                if (data[key] == null)
                {
                    return string.Empty;
                }
                else if (data[key].ToString() == "null")
                {
                    return string.Empty;
                }
                else
                {
                    return data[key].ToString();
                }

            }
            return string.Empty;
        }

        /// <summary>
        /// 根据key 获取value值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="dataJson"></param>
        /// <returns></returns>
        public static object GetDictionaryObject(string key, Dictionary<string, object> data)
        {
            if (data.ContainsKey(key))
            {
                return data[key];
            }
            return null;
        }
        public static object GetDictionaryObject(string key, Object dataobj)
        {
            Dictionary<string, object> data = dataobj as Dictionary<string, object>;
            return GetDictionaryObject(key, data);
        }


        #region 获取Json字符串某节点的值
        /// <summary>
        /// 获取Json字符串某节点的值
        /// </summary>
        public static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim('"') + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号，若是最后一个，截“｝”号，取最小值
                    int end = jsonStr.IndexOf(',', index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }

                    result = jsonStr.Substring(index, end - index);
                    result = result.Replace("}", "").Replace("]", "").Replace("\"", "");
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格

                    jsonStr = jsonStr.Remove(jsonStr.IndexOf(key), key.Length);
                    index = jsonStr.IndexOf(key) + key.Length + 1;
                    if (index > key.Length + 1)
                    {
                        result = result + "/" + GetJsonValue(jsonStr, key);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 获取Html字符串中指定标签的指定属性的值 
        /// </summary>
        /// <param name="html">Html字符</param>
        /// <param name="tag">指定标签名</param>
        /// <param name="attr">指定属性名</param>
        /// <returns></returns>
        private List<string> GetHtmlAttr(string html, string tag)
        {

            Regex re = new Regex(@"(<" + tag + @"[\w\W].)");
            MatchCollection imgreg = re.Matches(html);
            List<string> m_Attributes = new List<string>();
            Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);

            for (int i = 0; i < imgreg.Count; i++)
            {
                MatchCollection matchs = attrReg.Matches(imgreg[i].ToString());

                for (int j = 0; j < matchs.Count; j++)
                {
                    GroupCollection groups = matchs[j].Groups;

                    //if (attr.ToUpper() == groups[1].Value.ToUpper())
                    //{
                    //    m_Attributes.Add(groups[3].Value);
                    //    break;
                    //}
                }

            }

            return m_Attributes;

        }
        #endregion

    }
}